package org.anrc.poi;

import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

public class PoiRadar extends MapActivity {
	static final private int SHOW_MAIN_PREFERENCES = Menu.FIRST;
	static final private int SHOW_POI = Menu.FIRST + 1;
	static final private int SHOW_HELP = Menu.FIRST + 2;
	public static final String USER_PREFERENCES = "USER_PREFERENCES";
	public static final String PREF_VIEW_MY_LOCATION = "PREF_VIEW_MY_LOCATION";
	public static final String PREF_VIEW_MY_MAP = "PREF_VIEW_MY_MAP";
	public static final String PREF_VIEW_MY_COMPAS = "PREF_VIEW_MY_COMPAS";
	public static final String PREF_ALERT_RADIUS = "PREF_ALERT_RADIUS";

	private TextView myLocationText;
	private MapView myMapView;
	public static Location myLocation;
	MapController mapController;
	MyPositionOverlay positionOverlay;
	SharedPreferences prefs;
	Cursor poiCursor;

	PoiReceiver receiver;
	NotificationManager notificationManager;

	LinearLayout linearLayout;
	ZoomControls mZoom;

	@Override
	protected void onDestroy() {
		poiCursor.close();
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		poiCursor.deactivate();
		super.onPause();
	}

	@Override
	protected void onResume() {
		notificationManager.cancel(PoiListService.NOTIFICATION_ID);
		poiCursor.requery();
		IntentFilter filter;
		filter = new IntentFilter(PoiListService.NEW_POI_FOUND);
		receiver = new PoiReceiver();
		registerReceiver(receiver, filter);

		super.onResume();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		//
		switch (item.getItemId()) {
		case (SHOW_MAIN_PREFERENCES): {
			Intent i = new Intent(this, MainPreferences.class);
			startActivityForResult(i, SHOW_MAIN_PREFERENCES);
			return true;
		}
		case (SHOW_POI): {
			Intent i = new Intent(this, PoiList.class);
			startActivityForResult(i, SHOW_POI);
			return true;
		}
		case (SHOW_HELP): {
			Intent i = new Intent(this, HelpActivity.class);
			startActivityForResult(i, SHOW_HELP);
			return true;
		}
		}
		return false;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// widok mapy
		setMapView();
	}

	private void setMapView() {
		myLocationText = (TextView) findViewById(R.id.myLocationText);
		myMapView = (MapView) findViewById(R.id.myMapView);

		String svcName = Context.NOTIFICATION_SERVICE;
		notificationManager = (NotificationManager) getSystemService(svcName);

		LocationManager locationManager;
		String context = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) getSystemService(context);
		mapController = myMapView.getController();

		List<Overlay> overlays = myMapView.getOverlays();

		// POI
		Uri poiURI = PoiProvider.CONTENT_URI;
		ContentResolver cr = getContentResolver();
		poiCursor = cr.query(poiURI, null, null, null, null);

		PoiOverlay poiOverlay = new PoiOverlay(poiCursor, myMapView);
		overlays.add(poiOverlay);

		// Zoom
		linearLayout = (LinearLayout) findViewById(R.id.myZoomView);
		mZoom = (ZoomControls) myMapView.getZoomControls();
		linearLayout.addView(mZoom);
		myMapView.getController().setZoom(11);

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);

		String provider = locationManager.getBestProvider(criteria, true);

		myLocation = locationManager.getLastKnownLocation(provider);

		// My Position
		positionOverlay = new MyPositionOverlay(myMapView, myLocation);
		overlays.add(positionOverlay);

		updateWithNewLocation(myLocation);

		locationManager.requestLocationUpdates(provider, 2000, 10,
				locationListner);

	}

	private final LocationListener locationListner = new LocationListener() {

		public void onLocationChanged(Location location) {
			myLocation = location;
			updateWithNewLocation(location);
			runAlert();

		}

		public void onProviderDisabled(String provider) {
			updateWithNewLocation(null);
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

	};

	private void updateWithNewLocation(Location location) {
		String locationString;

		// update zaznaczenia lokacji
		positionOverlay.setLocation(location);

		// update lokacji na mapie
		Double geoLat = location.getLatitude() * 1E6;
		Double geoLng = location.getLongitude() * 1E6;
		GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue());
		mapController.animateTo(point);

		double lat = location.getLatitude();
		double lng = location.getLongitude();
		locationString = "Szer: " + lat + " \nDlug: " + lng;

		myLocationText.setText(locationString);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, SHOW_MAIN_PREFERENCES, Menu.NONE,
				R.string.show_view_main_settings_prompt);

		menu.add(0, SHOW_POI, Menu.NONE, R.string.show_view_poi_string);
		menu.add(0, SHOW_HELP, Menu.NONE, R.string.show_view_help_string);

		return true;
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	private void runAlert() {
		startService(new Intent(this, PoiRadarService.class));
	}

	public class PoiReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			notificationManager.cancel(PoiListService.NOTIFICATION_ID);

			poiCursor.requery();
			MapView poiMap = (MapView) findViewById(R.id.myMapView);
			poiMap.invalidate();
		}
	}
}